//
//  SearchTableViewController.m
//  BobNews
//
//  Created by lanou3g on 16/5/18.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "SearchTableViewController.h"
#import "NetWorkRequestManager.h"
#import "ToutiaoModel.h"
#import "ToutiaoArticleViewController.h"
#import "ToutiaoSpeciaTableController.h"
#import "ToutiaoPhotoViewController.h"

#import "LORefresh.h"

@interface SearchTableViewController ()<UISearchResultsUpdating>

@property (nonatomic,strong) NSMutableArray *array;
@property (nonatomic,strong) NSMutableArray *dataSourceArray;
@property (nonatomic,strong) NSMutableArray *searchResult;
@property (nonatomic,strong) UISearchController *searchController;
@property (nonatomic,strong) NSMutableArray *dataSoure;


@end

@implementation SearchTableViewController
- (void)dealloc {
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
 
    self.array = [NSMutableArray new];
    self.dataSoure = [NSMutableArray new];
    self.dataSourceArray = [NSMutableArray new];
    
    [self analyticalData];
    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    // 设置代理
    _searchController.searchResultsUpdater = self;
    // 设置半透明背景，当设置当前视图控制器作为搜索结果的视图控制器时，要设为NO；
    _searchController.dimsBackgroundDuringPresentation = NO;
    // 因此导航栏
    _searchController.hidesNavigationBarDuringPresentation = NO;
    // 关掉自动大写锁定
    _searchController.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    // 设置searchBar的frame
    _searchController.searchBar.frame = CGRectMake(0, 44, CGRectGetWidth(self.view.bounds), 44);

    self.tableView.tableHeaderView = self.searchController.searchBar;
 
    [self addRefresh];
    
}

- (void)addRefresh {
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.dataSoure removeAllObjects];
        [weakSelf.tableView reloadData];
        
        [weakSelf analyticalData];
    }];
    
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        
        [weakSelf analyticalData];
    }];

}


- (void)analyticalData {
    //@"http://c.3g.163.com/nc/article/headline/T1348647909107/0-20.html?from=toutiao&size=20&passport=&devId=2vqQCWgxR7%2FxNM4EyVV6Aw%3D%3D&lat=&lon=&version=7.0&net=wifi&ts=1462501207&sign=0Y0Oh7WXbXvg%2F6S6pt7ccBD5Dxs6eLvJygsqTC1fyn548ErR02zJ6%2FKXOnxX046I&encryption=1&canal=miliao_news"
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:self.urlStr] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            
            NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSArray *array = jsonDic[@"T1348647909107"];
            
            
            for (NSDictionary *itemDic in array) {
                ToutiaoModel *model = [ToutiaoModel modelWithDictionary:itemDic];
                [self.dataSoure addObject:model];
                
                [self.dataSourceArray addObject:model.title];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                
                
                [[self.tableView defaultHeader]endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
            });
        }
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchController.active) {
        return _searchResult.count;
    }else{
        return _dataSourceArray.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    
    // 如果用户正在搜索，则返回搜索结果对应的数据，否则直接返回数据数组对应的数据；
    if (self.searchController.active) {
        cell.textLabel.text = _searchResult[indexPath.row];
    }else {
        cell.textLabel.text = _dataSourceArray[indexPath.row];
    }
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.searchController.active) {
        
        ToutiaoModel *model = self.array[indexPath.row];
        NSString *special = model.specialID;
        NSString *photo = model.photosetID;
        NSString *reSource = model.recSource;
        //    NSString *tag = model.TAG;
        //    NSString *video = model.videoID;
        if (special) {
            ToutiaoSpeciaTableController *specialTVC = [[ToutiaoSpeciaTableController alloc]init];
            specialTVC.specialID = model.specialID;
            specialTVC.navTitle = model.title;
            [self.navigationController pushViewController:specialTVC animated:YES];
        } else if (photo || [reSource isEqualToString:@"图集"]) {
            ToutiaoPhotoViewController *photoVC = [[ToutiaoPhotoViewController alloc]init];
            photoVC.navTitle = model.title;
            photoVC.photosetID = model.photosetID;
            NSLog(@"%@",model.photosetID);
            [self presentViewController:photoVC animated:YES completion:^{
                
            }];
        }
        else {
            ToutiaoArticleViewController *articalVC = [[ToutiaoArticleViewController alloc]init];
            articalVC.docid = model.docid;
            articalVC.navTitle = model.title;
            articalVC.model = model;
            [self.navigationController pushViewController:articalVC animated:YES];
        }
        self.searchController.hidesBottomBarWhenPushed = YES;
        
    } else {
        /*
        self.searchController.hidesBottomBarWhenPushed = YES;
        ToutiaoModel *model = self.dataSoure[indexPath.row];
        NSString *special = model.specialID;
        NSString *photo = model.photosetID;
        NSString *reSource = model.recSource;
        //    NSString *tag = model.TAG;
        //    NSString *video = model.videoID;
        if (special) {
            ToutiaoSpeciaTableController *specialTVC = [[ToutiaoSpeciaTableController alloc]init];
            specialTVC.specialID = model.specialID;
            specialTVC.navTitle = model.title;
            [self.navigationController pushViewController:specialTVC animated:YES];
        } else if (photo || [reSource isEqualToString:@"图集"]) {
            ToutiaoPhotoViewController *photoVC = [[ToutiaoPhotoViewController alloc]init];
            photoVC.navTitle = model.title;
            photoVC.photosetID = model.photosetID;
            NSLog(@"%@",model.photosetID);
            [self presentViewController:photoVC animated:YES completion:^{
                
            }];
        }
        else {
            ToutiaoArticleViewController *articalVC = [[ToutiaoArticleViewController alloc]init];
            articalVC.docid = model.docid;
            articalVC.navTitle = model.title;
            articalVC.model = model;
            [self.navigationController pushViewController:articalVC animated:YES];
        }
        
        self.searchController.active = NO;
         */

    }
    
  
    // 停止搜索
    self.searchController.active = NO;
    
}


- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    // 获取搜索框里地字符串
    NSString *searchString = searchController.searchBar.text;
    
    // 谓词
    /**
     1.BEGINSWITH ： 搜索结果的字符串是以搜索框里的字符开头的
     2.ENDSWITH   ： 搜索结果的字符串是以搜索框里的字符结尾的
     3.CONTAINS   ： 搜索结果的字符串包含搜索框里的字符
     
     [c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写，也不区分发音符号。
     
     */
    
    // 创建谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH [CD] %@", searchString];
    // 如果搜索框里有文字，就按谓词的匹配结果初始化结果数组，否则，就用字体列表数组初始化结果数组。
    if (_searchResult != nil && searchString.length > 0) {
        [_searchResult removeAllObjects];
        _searchResult = [NSMutableArray arrayWithArray:[_dataSourceArray filteredArrayUsingPredicate:predicate]];
        
        
        for (ToutiaoModel *model in self.dataSoure) {
            NSString *title = model.title;
            BOOL is = [title containsString:searchString];
            if (is) {
                [self.array addObject:model];
            }
        }
        
    } else if (searchString.length == 0) {
        _searchResult = [NSMutableArray arrayWithArray:_dataSourceArray];
    }
    
    // 刷新表格视图
    [self.tableView reloadData];
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
